package org.hiucung.orangeppjoke;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import org.hiucung.libcommon.utils.StatusBar;
import org.hiucung.libnetwork.ApiResponse;
import org.hiucung.libnetwork.GetRequest;
import org.hiucung.libnetwork.JsonCallback;
import org.hiucung.orangeppjoke.model.Destination;
import org.hiucung.orangeppjoke.model.User;
import org.hiucung.orangeppjoke.ui.login.UserManager;
import org.hiucung.orangeppjoke.utils.AppConfig;
import org.hiucung.orangeppjoke.utils.NavGraphBuilder;
import org.hiucung.orangeppjoke.view.AppBottomBar;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private NavController navController;

    private AppBottomBar navView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //由于 启动时设置了 R.style.launcher 的windowBackground属性
        //势必要在进入主页后,把窗口背景清理掉
        setTheme(R.style.AppTheme);
        //启用沉浸式布局，白底黑字
        StatusBar.fitSystemBar(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.WRITE_EXTERNAL_STORAGE,
                            Permission.READ_PHONE_STATE,
                            Permission.READ_EXTERNAL_STORAGE)
                    .onGranted(permissions -> { })
                    .start();
        }

        navView = findViewById(R.id.nav_view);

        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        if (fragment != null) {
            navController = NavHostFragment.findNavController(fragment);
            NavGraphBuilder.build(navController, this, fragment.getId());
        }

        navView.setOnNavigationItemSelectedListener(this);

    }

    /**
     * 改造内部的fragment切换方式，底层是replase，改成show和hide
     *
     * @param menuItem
     * @return
     */

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();

        Iterator<Map.Entry<String, Destination>> iterator = destConfig.entrySet().iterator();

        while (iterator.hasNext()){
            Map.Entry<String, Destination> entry = iterator.next();
            Destination value = entry.getValue();

            if (value != null && !UserManager.get().isLogin() && value.needLogin && value.id == menuItem.getItemId()){
                UserManager.get().login(this).observe(this, new Observer<User>() {
                    @Override
                    public void onChanged(User user) {
                        navView.setSelectedItemId(menuItem.getItemId());
                    }
                });
                return false;
            }
        }
        navController.navigate(menuItem.getItemId());
        return !TextUtils.isEmpty(menuItem.getTitle());
    }

    @Override
    public void onBackPressed() {
        //当前正在显示的页面destinationId
        int currentPageId = navController.getCurrentDestination().getId();

        //APP页面路导航结构图  首页的destinationId
        int homeDestId = navController.getGraph().getStartDestination();

        //如果当前正在显示的页面不是首页，而我们点击了返回键，则拦截。
        if (currentPageId != homeDestId) {
            navView.setSelectedItemId(homeDestId);
            return;
        }

        //否则 finish，此处不宜调用onBackPressed。因为navigation会操作回退栈,切换到之前显示的页面。
        finish();
    }
}
